package com.minhua.jijiehao2.mainframe.circle.companyIdentifyActivity.impl

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v4.content.FileProvider
import android.support.v7.app.AlertDialog
import android.view.Gravity
import android.view.View
import com.baidu.ocr.sdk.model.IDCardParams
import com.minhua.jijiehao2.R
import com.minhua.jijiehao2.base.BaseActivity
import com.minhua.jijiehao2.bean.LicenseRecognitionBean
import com.minhua.jijiehao2.mainframe.circle.companyIdentifyActivity.imp.CompanyIdentifyView
import com.minhua.jijiehao2.mainframe.circle.productServiceActivity.impl.ProductServiceActivity
import com.minhua.jijiehao2.mainframe.mine.companyResultActivity.impl.CompanyResultActivity
import com.minhua.jijiehao2.utils.*
import com.minhua.jijiehao2.view.CustomDialog
import kotlinx.android.synthetic.main.activity_identify.*
import java.io.File


class CompanyIdentifyActivity : BaseActivity<CompanyIdentifyView, CompanyIdentifyPresenter>(), CompanyIdentifyView {

    override fun getLayoutId(): Int = R.layout.activity_identify

    override fun getPresenter(): CompanyIdentifyPresenter = CompanyIdentifyPresenter()

    private var dialog: CustomDialog? = null

    private val licenseCameraCode = 1000
    private val frontIDCardCameraCode = 1001
    private val backIDCardCameraCode = 1002
    private val photoCameraCode = 1003

    private val licenseAlbumCode = 1004
    private val frontIDCardAlbumCode = 1005
    private val backIDCardAlbumCode = 1006
    private val photoAlbumCode = 1007

    private var introduction = ""
    private val introductionCode = 1008

    private val permissionCameraCode = 1
    private val permissionStorageCode = 2

    private var currentCameraCode = licenseCameraCode
    private var currentAlbumCode = licenseAlbumCode
    private val mOnClickListener = View.OnClickListener { v ->
        when (v.id) {
            R.id.tvCamera -> {
                startCamera()
                dialog?.dismiss()
            }
            R.id.tvAlbum -> {
                startAlbum()
                dialog?.dismiss()
            }
            R.id.tvCancel -> dialog?.dismiss()
            R.id.ivGetLicense -> {
                currentCameraCode = licenseCameraCode
                currentAlbumCode = licenseAlbumCode
                dialog?.show()
            }
            R.id.ivGetFrontIDCard -> {
                currentCameraCode = frontIDCardCameraCode
                currentAlbumCode = frontIDCardAlbumCode
                dialog?.show()
            }
            R.id.ivGetBackIDCard -> {
                currentCameraCode = backIDCardCameraCode
                currentAlbumCode = backIDCardAlbumCode
                dialog?.show()
            }
            R.id.ivGetPhoto -> {
                currentCameraCode = photoCameraCode
                currentAlbumCode = photoAlbumCode
                dialog?.show()
            }
            R.id.tvEntry -> mPresenter.uploadCompanyInfo()
            R.id.tvIntroduction -> ProductServiceActivity.intentStart(this, "公司简介", introduction, introductionCode)

        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            permissionCameraCode -> {
                grantResults
                        .filter { it != PackageManager.PERMISSION_GRANTED }
                        .forEach {
                            T.showShort("必须同意所有该类权限才能使用本程序")
                            return
                        }
                toCamera()
            }
            permissionStorageCode -> {
                grantResults
                        .filter { it != PackageManager.PERMISSION_GRANTED }
                        .forEach {
                            T.showShort("必须同意所有该类权限才能使用本程序")
                            return
                        }
                toAlbum()
            }
        }
    }


    @SuppressLint("InlinedApi")
    private fun startAlbum() {
        if (ContextCompat.checkSelfPermission(
                this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(
                    this, Manifest.permission.READ_EXTERNAL_STORAGE)
                    || SPUtils.get(Manifest.permission.READ_EXTERNAL_STORAGE, false) as Boolean) {
                AlertDialog.Builder(this)
                        .setTitle("提示")
                        .setMessage("当前应用缺少读写权限。\n请点击\"设置\",\"权限\"打开相应权限")
                        .setPositiveButton("设置") { _, _ -> AppUtils.getAppDetailSettingIntent(this@CompanyIdentifyActivity) }
                        .setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
                        .create()
                        .show()
            } else {
                ActivityCompat.requestPermissions(
                        this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), permissionStorageCode)
                SPUtils.put(Manifest.permission.READ_EXTERNAL_STORAGE, true)
            }
        } else {
            toAlbum()
        }
    }

    private fun startCamera() {
        if (ContextCompat.checkSelfPermission(
                this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(
                    this, Manifest.permission.CAMERA)
                    || SPUtils.get(Manifest.permission.CAMERA, false) as Boolean) {
                AlertDialog.Builder(this)
                        .setTitle("提示")
                        .setMessage("当前应用缺少相机权限。\n请点击\"设置\",\"权限\"打开相应权限")
                        .setPositiveButton("设置") { _, _ -> AppUtils.getAppDetailSettingIntent(this@CompanyIdentifyActivity) }
                        .setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
                        .create()
                        .show()
            } else {
                ActivityCompat.requestPermissions(
                        this, arrayOf(Manifest.permission.CAMERA), permissionCameraCode)
                SPUtils.put(Manifest.permission.CAMERA, true)
            }
        } else {
            toCamera()
        }
    }

    private var outputFile: File? = null

    private fun toCamera() {
        outputFile = File(FileUtils.getCatchFileDir("img"), "$currentCameraCode.jpg")

        if (outputFile!!.exists()) {
            outputFile!!.delete()
        }
        outputFile!!.createNewFile()
        //调用摄像头action
        val pIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        var imageUri = Uri.fromFile(outputFile)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            pIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            imageUri = FileProvider.getUriForFile(this, "com.minhua.jijiehao2.fileprovider", outputFile)
        }
        pIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
        startActivityForResult(pIntent, currentCameraCode)
    }

    private fun toAlbum() {
        val intent = Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, currentAlbumCode)
    }


    override fun initView() {
        ivGetLicense.setOnClickListener(mOnClickListener)
        ivGetFrontIDCard.setOnClickListener(mOnClickListener)
        ivGetBackIDCard.setOnClickListener(mOnClickListener)
        ivGetPhoto.setOnClickListener(mOnClickListener)
        dialog = CustomDialog(this, R.layout.layout_dialog_photo_menu, false, Gravity.BOTTOM)
        dialog?.viewHolder?.setOnClickListener(R.id.tvCamera, mOnClickListener)
        dialog?.viewHolder?.setOnClickListener(R.id.tvAlbum, mOnClickListener)
        dialog?.viewHolder?.setOnClickListener(R.id.tvCancel, mOnClickListener)
        tvEntry.setOnClickListener(mOnClickListener)
    }


    private var licenceBit: Bitmap? = null
    private var frontBit: Bitmap? = null
    private var backBit: Bitmap? = null
    private var photoBit: Bitmap? = null

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                licenseCameraCode, frontIDCardCameraCode, backIDCardCameraCode, photoCameraCode -> {
                    val bit = BitmapUtils.getBitmap(outputFile, 200, 200, false)
                    LoadingDialogUtil.showDialog(this)
                    when (requestCode) {
                        licenseCameraCode -> {
                            licenceBit = bit
                            ivLicense.setImageBitmap(licenceBit)
                            mPresenter.identifyLicense(bit, requestCode)
                        }
                        frontIDCardCameraCode -> {
                            frontBit = bit
                            ivPersonFront.setImageBitmap(frontBit)
                            mPresenter.identifyIDCard(bit, IDCardParams.ID_CARD_SIDE_FRONT, requestCode)
                        }
                        backIDCardCameraCode -> {
                            backBit = bit
                            ivPersonBack.setImageBitmap(backBit)
                            mPresenter.identifyIDCard(bit, IDCardParams.ID_CARD_SIDE_BACK, requestCode)
                        }
                        photoCameraCode -> {
                            photoBit = bit
                            ivPersonPhoto.setImageBitmap(photoBit)
                            mPresenter.uploadImage(bit, requestCode)
                        }
                    }
                }

                licenseAlbumCode, frontIDCardAlbumCode, backIDCardAlbumCode, photoAlbumCode -> {
                    val bit = if (SystemUtils.isMIUI()) {
                        BitmapUtils.setPhotoForMiuiSystem(this, data, 200, 200)
                    } else {
                        BitmapUtils.getPhotoForNormalSystem(this, data, 200, 200)
                    }
                    LoadingDialogUtil.showDialog(this)
                    when (requestCode) {
                        licenseAlbumCode -> {
                            licenceBit = bit
                            ivLicense.setImageBitmap(licenceBit)
                            mPresenter.identifyLicense(bit, requestCode)
                        }
                        frontIDCardAlbumCode -> {
                            frontBit = bit
                            ivPersonFront.setImageBitmap(frontBit)
                            mPresenter.identifyIDCard(bit, IDCardParams.ID_CARD_SIDE_FRONT, requestCode)
                        }
                        backIDCardAlbumCode -> {
                            backBit = bit
                            ivPersonBack.setImageBitmap(backBit)
                            mPresenter.identifyIDCard(bit, IDCardParams.ID_CARD_SIDE_BACK, requestCode)
                        }
                        photoAlbumCode -> {
                            photoBit = bit
                            ivPersonPhoto.setImageBitmap(photoBit)
                            mPresenter.uploadImage(bit, requestCode)
                        }
                    }
                }
                introductionCode -> {
                    introduction = data?.getStringExtra("text") as String
                }
            }
        }
    }

    private var licensePic: String? = null
    private var identityFrontPic: String? = null
    private var identityReversePic: String? = null
    private var holdCardPic: String? = null
    override fun onUploadImageSuccess(requestCode: Int, location: String) {
        when (requestCode) {
            licenseCameraCode, licenseAlbumCode -> licensePic = location
            frontIDCardCameraCode, frontIDCardAlbumCode -> identityFrontPic = location
            backIDCardCameraCode, backIDCardAlbumCode -> identityReversePic = location
            photoCameraCode, photoAlbumCode -> holdCardPic = location
        }
    }

    override fun onUploadInfoSuccess() {
        T.showShort("上传成功")
        startActivity(Intent(this, CompanyResultActivity::class.java))
    }

    override fun onLicenseSuccess(licenseRecognitionBean: LicenseRecognitionBean) {
        val info = licenseRecognitionBean.words_result
        tvCompanyName.text = info.单位名称.words
    }

    override fun companyName(): String = tvCompanyName.text

    override fun legalPersonName(): String = tvLegalPersonName.text

    override fun iDNumber(): String = tvIDNumber.text

    override fun contactPerson(): String = tvContactPerson.text

    override fun contactTel(): String = tvContactTel.text

    override fun introduction(): String = introduction

    override fun licensePic(): String = licensePic ?: ""

    override fun identityFrontPic(): String = identityFrontPic ?: ""

    override fun identityReversePic(): String = identityReversePic ?: ""

    override fun holdCardPic(): String = holdCardPic ?: ""

}
